using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MKDS_Course_Editor.GCN.BMD
{
    class DRW1
    {
        public class Drw1Header
        {
            public string tag;
            public UInt32 sizeOfSection;
            public UInt16 count;
            public UInt16 pad;

            //stores for each matrix if it's weighted (normal (0)/skinned (1) matrix types)
            public UInt32 offsetToIsWeighted;

            //for normal (0) matrices, this is an index into the global matrix
            //table (which stores a matrix for every joint). for skinned
            //matrices (1), I'm not yet totally sure how this works (but it's
            //probably an offset into the Evp1-array)
            public UInt32 offsetToData;
        }

        public class Drw1
        {
            public List<bool> isWeighted = new List<bool>();
            public List<UInt16> data = new List<ushort>();
        }


        private static void readDrw1Header(EndianBinaryReader er, Drw1Header h)
        {
            h.tag = er.ReadString(Encoding.ASCII, 4);
            h.sizeOfSection = er.ReadUInt32();
            h.count = er.ReadUInt16();
            h.pad = er.ReadUInt16();
            h.offsetToIsWeighted = er.ReadUInt32();
            h.offsetToData = er.ReadUInt32();
        }

        public static void dumpDrw1(EndianBinaryReader er, Drw1 dst)
        {
            int drw1Offset = (int)er.BaseStream.Position, i;

            //read header
            Drw1Header h = new Drw1Header();
            readDrw1Header(er, h);

            //read bool array
            dst.isWeighted.AddRange(new bool[h.count]);
            er.BaseStream.Position = drw1Offset + h.offsetToIsWeighted;
            for (i = 0; i < h.count; ++i)
            {
                dst.isWeighted[i] = new bool();
                byte v = er.ReadByte();
                if (v == 0)
                    dst.isWeighted[i] = false;
                else if (v == 1)
                    dst.isWeighted[i] = true;
                else
                {
                    //warn("drw1: unexpected value in isWeighted array: %d", v);
                }
            }

            //read data array
            dst.data.AddRange(new ushort[h.count]);
            er.BaseStream.Position = drw1Offset + h.offsetToData;
            for (i = 0; i < h.count; ++i)
            {
                dst.data[i] = er.ReadUInt16();
            }
        }

    }
}
